package com.db.serialize;

import com.db.serialize.domain.SensorData;
import com.db.serialize.network.AbstractNetwork;
import com.db.serialize.serializer.SensorDataSerializer;
import com.db.serialize.serializer.SensorDataSerializerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class SerializeServer extends AbstractNetwork {
    public static void main(String[] args) {
        System.out.println("server started");

        SensorDataSerializer serializer = SensorDataSerializerFactory.getSerializer();
        List<SensorData> sensorDataList = new ArrayList<>();

        try (ServerSocket serverSocket = new ServerSocket(SERVER_PORT, SERVER_BACKLOG)) {
            System.out.println("connection started");

            try (Socket socket = serverSocket.accept();
                 ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                 ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream())) {

                System.out.println("client connected");

                for (int i = 0; i < ITERATION_COUNT; i++) {
                    Object data = objectInputStream.readObject();
                    SensorData sensorData = serializer.deSerialize(data);
                    sensorDataList.add(sensorData);
                }

                objectOutputStream.writeObject("recieved: " + sensorDataList.size());
                System.out.println("success");

            } catch (IOException e) {
                System.out.println("input output exception");
            } catch (ClassNotFoundException e) {
                System.out.println("class not found exception");
            }
        } catch (IOException e) {
            System.out.println("input output exception");
        }
    }
}
